<template>
  <div class="bg-white flex flex-col">
    <div class="w-[350px] m-auto flex flex-col md:w-[1440px] md:m-auto">
      <!-- Banner区域 -->
      <div class="relative w-full h-[600px] bg-gradient-to-r from-gray-800 to-gray-900 overflow-hidden">
        <!-- 背景图片 -->
        <div class="absolute inset-0">
          <img
            :src="currentBannerImage"
            class="w-full h-full object-cover cursor-pointer"
            @click="goToBannerDetail"
          />
        </div>
        
        <!-- 活动描述区域 - 悬浮在底部 -->
        <div class="absolute bottom-0 left-0 right-0 bg-black bg-opacity-75 h-[300px] z-10">
          <!-- 左右导航按钮 - 水平靠上对齐 -->
          <div v-if="bannerEvents.length > 1" class="absolute top-20 right-[30%] flex space-x-8 z-20"> <!-- 添加z-20提高层级 -->
            <!-- 左导航按钮 -->
            <button @click="changeBannerIndex(-1)" class="cursor-pointer">
              <img src="@/assets/images/arrow-right-grey.png" class="w-[37px] h-[37px] transform rotate-180">
            </button>
            <!-- 右导航按钮 -->
            <button @click="changeBannerIndex(1)" class="cursor-pointer">
              <img src="@/assets/images/arrow-right-grey.png" class="w-[37px] h-[37px]">
            </button>
          </div>
          
          <div class="absolute bottom-0 left-0 right-0 p-12">
            <div class="flex justify-between items-center mb-4">
              <!-- 左侧：新闻描述和邮箱按钮 -->
              <div class="flex flex-col max-w-[60%]">
                <h1 class="text-[27px] md:text-[27px] font-bold leading-tight text-white mb-2">
                  {{ currentBannerEvent?.title }}
                </h1>
                <div class="text-white text-[20px]">{{ formatDate(currentBannerEvent?.startDate) + ' ~ ' + formatDate(currentBannerEvent?.endDate) }}</div>
                <!-- 邮箱按钮 -->
                <a v-if="currentBannerEvent?.type 
                    && currentBannerEvent?.type=='limitOnline' 
                    && currentBannerEvent?.contact" 
                  :href="`mailto:${currentBannerEvent?.contact}`" 
                  class="bg-primary text-white px-4 py-2 mt-4 rounded-full flex items-center w-fit"
                >
                  {{ currentBannerEvent?.contact }}
                </a>
                <!-- 会议链接按钮 -->
                <a v-if="currentBannerEvent?.type
                    && currentBannerEvent?.type=='openOnline'
                    && currentBannerEvent?.meetingLink" 
                  :href="currentBannerEvent?.meetingLink"
                  target="_blank"
                  class="bg-primary text-white px-4 py-2 mt-4 rounded-full flex items-center w-fit">
                  {{ currentBannerEvent?.meetingLink }}
                </a>
              </div>
              
              <div class="flex items-center flex-2 mr-20">
                <!-- 日历图标按钮 -->
                <button v-if="!showDatePicker" @click="showDatePicker = !showDatePicker">
                  <img src="@/assets/images/calendar.png" alt="Calendar Icon" class="w-[80px]">
                </button>
                <!-- 日期选择器容器 -->
                <div v-if="showDatePicker" class="absolute right-16 -top-36 z-30">
                  <!-- 关闭按钮 -->
                  <div class="absolute -top-8 left-0 bg-primary w-full h-9 rounded-tl-[20px] rounded-tr-[20px] flex items-center justify-between px-4 z-20 text-white font-medium">
                    <span class="text-[17px]">Calendar of events</span>
                    <button @click="showDatePicker = false">
                      <img src="@/assets/images/close.png" class="w-[20px] h-[20px]">
                    </button>
                  </div>
                  <!-- 日期选择器 -->
                  <a-date-picker
                    v-model="pickerValue"
                    value-format="timestamp"
                    hide-trigger
                    style="width: 288px;"
                    @change="handleDatePickerSelect"
                    @picker-value-change="handleDatePickerChange"
                  >
                  <template #cell="{ date }">
                    <div class="arco-picker-date">
                      <div class="arco-picker-date-value" :style="getCellStyle(date)">
                        {{ date.getDate() }}
                      </div>
                    </div>
                  </template>
                  </a-date-picker>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 近期活动 -->
      <div class="w-[90%] m-auto flex justify-between items-center mt-8">
        <span class="text-[44px] text-primary font-bold">Upcoming Events</span> 
        <span class="flex flex-1 justify-end">
          <img src="@/assets/images/line.png" class="w-[95%]">
        </span>
      </div>

      <div class="w-full max-w-[1200px] m-auto flex justify-between items-center mt-4 mb-8">
        <div v-for="(item, index) in upcomingEvents" :key="index" class="flex-1 flex justify-center items-center relative my-12">
          <img src="@/assets/images/heart-bg.png" class="h-[295px] absolute" :class="index%2!==0?'transform rotate-180':''">
          <img 
            :src="item.coverImage" 
            @click="handleEventDetail(item.eid)" 
            class="w-[258px] h-[258px] rounded-[38px] relative z-10 object-cover cursor-pointer">
        </div>
      </div>

      <div class="m-auto w-[45%] flex justify-between items-center pb-[30px]">
        <!-- 左翻页按钮 -->
        <button
          @click="handleUpcomingPrevPage" 
          :disabled="upcomingEventsCurrentPage <= 1"
          :class="[
            'flex items-center justify-center hover:bg-gray-50 transition-all duration-300',
            { 'opacity-50': upcomingEventsCurrentPage <= 1 }
            ]">
          <img class="w-[50px] h-[50px]" src="@/assets/images/previous.png" />
        </button>
        
        <!-- 右翻页按钮 -->
        <button 
          @click="handleUpcomingNextPage"
          :disabled="upcomingEventsCurrentPage >= upcomingEventsTotalPages"
          :class="[
            'flex items-center justify-center hover:bg-gray-50 transition-all duration-300',
            { 'opacity-50': upcomingEventsCurrentPage >= upcomingEventsTotalPages }
            ]">
          <img class="w-[50px] h-[50px]" src="@/assets/images/next.png" />
        </button>
      </div>

      <!-- 往期活动 -->
      <div class="w-[90%] m-auto flex justify-between items-center">
        <span class="text-[44px] text-primary font-bold">Past Events</span> 
        <span class="flex flex-1 justify-end">
          <img src="@/assets/images/line.png" class="w-[95%]">
        </span>
      </div>

      <div v-for="(item, index) in pastEvents" :key="index" class="m-auto w-full max-w-[1200px]"> <!-- 添加最大宽度和宽度100% -->
        <SidedLayout
          type="eventReview"
          :title="item.title" 
          :desc="item.summary" 
          :bgImg="item.coverImage" 
          :date="item.createAt"
          :cid="item.cid"
        />
      </div>
      <div class="m-auto w-[45%] flex justify-between items-center pb-[30px]">
        <!-- 左翻页按钮 -->
        <button
          @click="handlePastPrevPage"
          :disabled="pastEventsCurrentPage <= 1"
          :class="[
            'flex items-center justify-center hover:bg-gray-50 transition-all duration-300',
            { 'opacity-50': pastEventsCurrentPage <= 1 }
            ]">
          <img class="w-[50px] h-[50px]" src="@/assets/images/previous.png" />
        </button>
        
        <!-- 右翻页按钮 -->
        <button
          @click="handlePastNextPage"
          :disabled="pastEventsCurrentPage >= pastEventsTotalPages"
          :class="[
            'flex items-center justify-center hover:bg-gray-50 transition-all duration-300',
            { 'opacity-50': pastEventsCurrentPage >= pastEventsTotalPages }
            ]">
          <img class="w-[50px] h-[50px]" src="@/assets/images/next.png" />
        </button>
      </div>
    </div>
    <!-- <FooterBg /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import SidedLayout from '@/components/SidedLayout.vue'
import { eventDetailApi, eventListApi } from '@/api/event'
import { formatDate, getCurrentMonthFirstDayTimestamp, getCurrentMonthLastDayTimestamp, getCurrentDayMidnightTimestamp, getTomorrowMidnightTimestamp } from '@/utils/tool'
import { contentDetailApi, contentListApi } from '@/api/content'
import { useRouter } from 'vue-router'

const router = useRouter()

// 日历选择时间
const pickerValue = ref()
const showDatePicker = ref(false) // 控制日期选择器的显示/隐藏

// Banner轮播数据
const bannerEvents = ref([] as any[])

const currentBannerIndex = ref(0)

// 计算当前显示的新闻和图片
const currentBannerEvent = computed(() => bannerEvents.value[currentBannerIndex.value])
const currentBannerImage = computed(() => bannerEvents.value[currentBannerIndex.value]?.coverImage)

// 自动轮播
let autoPlayTimer: NodeJS.Timeout

// 即将到来的活动
const upcomingEvents = ref([] as any[])

// 即将到来的活动当前页码
const upcomingEventsCurrentPage = ref(1)

// 即将到来的活动总页数
const upcomingEventsTotalPages = ref(0)

// 过去的活动
const pastEvents = ref([] as any[])

// 过去的活动当前页码
const pastEventsCurrentPage = ref(1)

// 过去的活动总页数
const pastEventsTotalPages = ref(0)

// 当月的活动
const currentMonthEvents = ref([] as any[])

const startAutoPlay = () => {
  autoPlayTimer = setInterval(() => {
    currentBannerIndex.value = (currentBannerIndex.value + 1) % bannerEvents.value.length
  }, 5000) // 5秒切换一次
}

const stopAutoPlay = () => {
  if (autoPlayTimer) {
    clearInterval(autoPlayTimer)
  }
}

const getRecommendEvents = async () => {
  let query = {
    recommend: true,
    page: 1,
    limit: 5
  }
  let results = await getEvents(query)
  Object.assign(bannerEvents.value, results)
  // 数据加载完成后启动轮播
  if (bannerEvents.value.length > 0) {
    startAutoPlay()
  }
}

// 修改 onMounted
onMounted(async () => {
  await getRecommendEvents()  // 等待数据加载完成
  // startAutoPlay() // 移除这里的调用
  getCurrentMonthEvents()
  getUpcomingEvents()
  getPastEvents()
})

const getUpcomingEvents = async (page: number = 1) => {
  // 获取明天0点0分0秒0毫秒的时间戳
  let tomorrow = getTomorrowMidnightTimestamp()
  
  let query = {
    page: page,
    limit: 3,
    startDate: tomorrow // 使用明天0点的时间戳
  }
  let results = await getEvents(query)
  Object.assign(upcomingEvents.value, results)
}

const getEvents = async (query: any) => {
  return new Promise(async (resolve) => {
    eventListApi(query).then(async (res: any) => {
      if (res.code === 0) {
        const promises = res.data.list.map(async (item: any) => {
          upcomingEventsTotalPages.value = Math.ceil(res.data.total/query.limit)
          let event: any = await getEventDetail(item.eid)
          return { ...event }
        })
        // 使用 Promise.all 来等待所有 Promise 完成，并获取结果
        const results = await Promise.all(promises)
        resolve(results) // 返回results作为函数的返回值
      } else {
        resolve([]) // 如果没有成功获取数据，返回空数组
      }
    })
    .catch(() => {
      resolve([]) // 发生错误时返回空数组
    })
  })
}

const getEventDetail = (eid: string): Promise<any> => {
	return new Promise((resolve) => {
		eventDetailApi(eid, 'display').then((res: any) => {
			if(res.code === 0) {
				resolve(res.data)
			} else {
				resolve({})
			}
		}).catch(() => {
			resolve({})
		})
	})
}

const getPastEvents = async (page: number = 1) => {
  let past = {
    recommend: true,
    category: 'eventReview',
    status: 'publish',
    page: page,
    limit: 3
  }
  const pastRes: any = await contentListApi(past)
  if (pastRes.code === 0 && pastRes.data && pastRes.data.list) {
    pastEventsTotalPages.value = Math.ceil(pastRes.data.total/past.limit)
    let promises = pastRes.data.list.map(async (item: any) => {
      let eventReview: any = await getContentDetail(item.cid)
      return eventReview
    })
    // 使用 Promise.all 来等待所有 Promise 完成，并获取结果
    const results = await Promise.all(promises)
    Object.assign(pastEvents.value, results)
  }
}

const getContentDetail = (cid: string): Promise<any> => {
	return new Promise((resolve) => {
		contentDetailApi(cid, 'display').then((res: any) => {
			if(res.code === 0) {
				resolve(res.data)
			} else {
				resolve({})
			}
		}).catch(() => {
			resolve({})
		})
	})
}

const changeBannerIndex = (offset: number) => {
  currentBannerIndex.value = (currentBannerIndex.value + offset + bannerEvents.value.length) % bannerEvents.value.length
  console.log(currentBannerIndex.value)
}

const handleUpcomingPrevPage = () => {
  if (upcomingEventsCurrentPage.value > 1) {
    getUpcomingEvents(--upcomingEventsCurrentPage.value)
  }
}

const handleUpcomingNextPage = () => {
  if (upcomingEventsCurrentPage.value < upcomingEventsTotalPages.value) {
    getUpcomingEvents(++upcomingEventsCurrentPage.value)
  }
}

const handlePastPrevPage = () => {
  if (pastEventsCurrentPage.value > 1) {
    getPastEvents(--pastEventsCurrentPage.value)
  }
}

const handlePastNextPage = () => {
  if (pastEventsCurrentPage.value < pastEventsTotalPages.value) {
    getPastEvents(++pastEventsCurrentPage.value)
  }
}

const handleEventDetail = (eid: string) => {
  router.push({
    path: '/events/detail',
    query: {
      eid: eid
    }
  })
}

const goToBannerDetail = () => {
  if (currentBannerEvent.value && currentBannerEvent.value.eid) {
    router.push({
      path: '/events/detail', // 修改路径，去掉 /layout
      query: {
        eid: currentBannerEvent.value.eid
      }
    })
  }
}

const getCurrentMonthEvents = async (date: Date = new Date()) => {
  // 获取当前月1号0点0分0秒0毫秒的时间戳
  let monthFirstDayTimestamp = getCurrentMonthFirstDayTimestamp(date)
  // 获取当前月最后一天23点59分59秒999毫秒的时间戳
  let monthLastDayTimestamp = getCurrentMonthLastDayTimestamp(date)

  let query = {
    page: 1,
    limit: 100,
    startAt: monthFirstDayTimestamp, // 使用当月1号的时间戳
    endAt: monthLastDayTimestamp  // 使用当月最后一天的时间戳
  }
  let res: any = await eventListApi(query)
  if (res.code === 0) {
    let events = res.data.list
    Object.assign(currentMonthEvents.value, events)
  }
}

const getCellStyle = (date: Date) => {
  const todayTimestamp = getCurrentDayMidnightTimestamp()
  for (let event of currentMonthEvents.value) {
    let startDate = new Date(event.startDate)
    startDate.setHours(0, 0, 0, 0)
    let endDate = new Date(event.endDate)
    endDate.setHours(23, 59, 59, 999)
    if (event.startDate&&event.endDate&&date.getTime() >= startDate.getTime() && date.getTime() <= endDate.getTime()) {
      if(date.getTime() !== pickerValue.value) {
        if(date.getTime() >= todayTimestamp) {
          return 'color: #FFFFFF; background-color: #165DFF80;'
        } else {
          return 'color: #FFFFFF; background-color: #D8D8D8;'
        }
      }
    }
  }
}

const handleDatePickerChange = (value: Date, date: Date, dateString: string) => {
  getCurrentMonthEvents(date)
}

const handleDatePickerSelect = async (value: Date, date: Date, dateString: string) => {
  let startAt = getCurrentDayMidnightTimestamp(date)
  let endAt = startAt + (24 * 60 * 60 * 1000) - 1 // 一天的毫秒数

  let query = {
    page: 1,
    limit: 100,
    startAt: startAt,
    endAt: endAt
  }
  let results = await getEvents(query)
  Object.assign(bannerEvents.value, results)
}

// 组件挂载时执行
onMounted(() => {
  getRecommendEvents()
  startAutoPlay()
  getCurrentMonthEvents()
  getUpcomingEvents()
  getPastEvents()
})

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  stopAutoPlay()
})
</script>

<style scoped>
/* 可以添加一些自定义样式 */
.banner-transition {
  transition: all 0.5s ease-in-out;
}

:deep(.arco-picker-container) {
  border-radius: 0 0 20px 20px;
}
</style>import router from '@/router'

